/* =============================================================
 * Your Grandmother's guide to Algorithms
 * =============================================================
 *
 * Copyright (c) 2007, Saverio Miroddi
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright 
 *       notice, this list of conditions and the following disclaimer in the 
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the SaverioMiroddiSoftware nor the names of its 
 *       contributors may be used to endorse or promote products derived from 
 *       this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *  
 * ---------------------------
 * SavMath.java
 * ---------------------------
 *
 */
package utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * Random and basic math functions not included in java.lang.Math
 * 
 * @author Saverio Miroddi
 */
@SuppressWarnings("unchecked")
public class SavMath
{
	private static final Random rnd = new Random();

	/**
	 * Log base 2
	 * 
	 * @deprecated see {@link SavMath#log(int, int) general logarithm}
	 */
	@Deprecated
	public static double log2(int i)
	{
		return log(i, 2);
	}
	
	public static double log(double number, int base)
	{
		return Math.log(number)/Math.log(base);
	}

	/**
	 * Approx to the nearest power of two.
	 * 
	 * @param doCeil
	 *            true for ceil, false for floor.
	 */
	public static int power2approx(int num, boolean doCeil)
	{
		double log2num = log2(num);
		double log2appr = doCeil ? 
				Math.ceil(log2num) : Math.floor(log2num);
		return (int)Math.pow(2, log2appr);
	}
	
	public static <T extends Comparable> T min(T a, T b)
	{
		return a.compareTo(b) < 0 ? a : b;
	}

	public static <T extends Comparable> T max(T a, T b)
	{
		return a.compareTo(b) > 0 ? a : b;
	}

	/**
	 * Generate an array of random Bytes.<b>
	 * Useful for using random Comparable[s].
	 * 
	 * @param maxLen inclusive
	 */
	public static Byte[] getRandomBytes(int minLen, int maxLen)
	{
		int len = minLen + rnd.nextInt(maxLen - minLen + 1);
		
		byte[] buffer = new byte[len];
		rnd.nextBytes(buffer);
		
		Byte[] dest = new Byte[buffer.length];
		for (int i = 0; i < buffer.length; i++) dest[i] = buffer[i];
		
		return dest;
	}
	
	public static List<Integer> getRandomInts(
			int len, int maxNum, boolean allowDuplicates)
	{
		List<Integer> list = new ArrayList<Integer>();

		if (allowDuplicates) {
			for (int i = 0; i < len; i++) list.add(rnd.nextInt(maxNum));
		}
		else {
			for (int i = 0; i < len; i++) list.add(i);
			Collections.shuffle(list);
		}
		
		return list;
	}
	
	/**
	 * Get a serie long (numIntervals) of total random floats where, for every
	 * element, x &#060;= 1.0 and x<sub>i</sub> &#060;= x<sub>i+1</sub>
	 */
	public static float[] getRandomIntervals(int numIntervals)
	{
		float sum = 0f;
		float[] intervals = new float[numIntervals];
		
		for (int i = 0; i < numIntervals; i++) {
			float rndVal = rnd.nextFloat();
			
			intervals[i] = rndVal;
			sum += intervals[i];
		}
		
		float lastSum = 0f;
		
		for (int i = 0; i < numIntervals; i++) {
			float newInterval = intervals[i] / sum;
			
			intervals[i] = lastSum + newInterval;
			lastSum += newInterval;
		}
		
		return intervals;
	}
	
	/** Get the position of a random number in the intervals passed. */
	public static int getRandomPosition(float[] intervals) 
	{
		float rndVal = rnd.nextFloat();
		
		for (int i = 0; i < intervals.length; i++)
			if (rndVal < intervals[i]) return i;
		
		throw new AssertionError();
	}
}